<template>
  <div v-if="visible">
    <el-dialog title="导出" :visible.sync="visible" append-to-body width="555px" :show-close="false">
      <avue-form ref="form" v-model="form" :option="localOption">
        <template slot-scope="{ row }" slot="type">
          <el-radio-group v-model="form.type" @change="handleChange">
            <el-radio label="current" class="custom-radio">当前页面数据</el-radio>
            <el-radio label="all" class="custom-radio">全部数据(当前最大仅支持五百条数据下载)</el-radio>
          </el-radio-group>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport" size="small" :disabled="loading">导出</el-button>
        <el-button size="small" @click="handleClose">取消</el-button>
      </span>
    </el-dialog>
    <div class="pdf-warpper">
      <div class="pdf-content" :style="{ width: width + 'px' }" id="pdf">
        <chart-view :style="{ width: width + 'px' }" :chart-option="newChartOption" :auto-resize="true" />
        <avue-crud :style="{ width: width + 'px' }" :option="newOption" :data="data"> </avue-crud>
      </div>
    </div>
  </div>
</template>

<script>
// import { excel, calcCascader, detail } from '@/components/export-excel/util';
import { Message } from 'element-ui';
import request from '@/router/axios';
import ChartView from '@/components/chart/index.vue';
export default {
  name: 'export-pdf',
  components: {
    ChartView
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    option: {
      type: Object,
      default: () => ({})
    },
    chartOption: {
      type: Object,
      default: () => ({})
    },
    page: {
      type: Object,
      default: () => ({})
    },
    query: {
      type: Object,
      default: () => ({})
    },
    pdfConfig: {
      type: Object,
      default: () => ({ unit: 'pt', format: 'a4', orientation: 'portrait' })
    },
    name: {
      type: String,
      default: ''
    },
    url: {
      type: String,
      default: ''
    },
    data: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      showFlag: false,
      data: [],
      newOption: {},
      newChartOption: {},
      width: 800,
      localOption: {
        row: true,
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 130,
        column: [
          {
            label: '文件名',
            prop: 'name',
            span: 24
          },
          {
            label: '选择数据',
            prop: 'type',
            type: 'radio',
            value: 'current',
            span: 24
          },
          {
            label: '选择字段',
            prop: 'prop',
            type: 'tree',
            multiple: true,
            tags: false,
            checkStrictly: true,
            span: 24,
            props: {
              value: 'prop'
            },
            dicData:
              this._cloneDeep(this.option).column.filter((item) => {
                item.disabled = false;
                return !item.hide;
              }) || [],
            change: ({ value }) => {
              this.handleTableChange(value);
            }
          },
          {
            label: '参数设置',
            prop: 'params',
            type: 'checkbox',
            span: 24,
            dicData: [
              {
                label: '表头',
                disabled: true,
                value: 'header'
              },
              {
                label: '数据源',
                value: 'data'
              }
            ],
            value: ['header', 'data']
          },
          {
            label: '导出文件格式',
            prop: 'format',
            type: 'radio',
            span: 24,
            dicData: [
              {
                label: 'PDF',
                value: 'pdf'
              }
            ],
            value: 'pdf'
          }
        ]
      },
      columnOption: [],
      form: {
        name: this.name,
        type: 'current'
      }
    };
  },
  computed: {
    isDisabled() {
      return this.form.data !== 'custom';
    }
    // propOption() {
    //   let result = [];
    //   function findProp(list = []) {
    //     if (!Array.isArray(list)) return;
    //     list.forEach((ele) => {
    //       if (Array.isArray(ele.children)) findProp(ele.children);
    //       else result.push(ele);
    //     });
    //   }
    //   findProp(this.columnOption);
    //   result = calcCascader(result);
    //   return result;
    // },
    // resultOption() {
    //   return Object.assign(this._cloneDeep(this.newOption), {
    //     column: this.propOption
    //   });
    // }
  },
  mounted() {},
  methods: {
    openDialog() {
      this.newOption = {
        ...this._cloneDeep(this.option),
        menu: false,
        columnBtn: false,
        refreshBtn: false,
        height: '100vh'
      };
      let { format, k } = this.getPdfConfig(this.pdfConfig.format, this.pdfConfig.unit);
      this.width = (format[0] > format[1] ? format[1] : format[0]) * (k / 72) * 96;
      console.log(this.width, format, k, format[0] > format[1] ? format[1] : format[0]);
      this.newChartOption = this._cloneDeep(this.chartOption);
      this.getColumnOption();
      this.visible = true;
    },
    handleExport() {
      this.$message.warning('导出中，请稍等...');
      this.data = [];
      try {
        // this.getColumn();
        request({
          url: this.url,
          method: 'GET',
          params: {
            ...this.query,
            size: this.form.type === 'all' ? 500 : this.page.pageSize,
            current: this.form.type === 'all' ? 1 : this.page.currentPage
          }
        })
          .then((res) => {
            let data = res.data.data;
            this.data = data.records || [];
            this.$nextTick(() => {
              const ele = document.getElementById('pdf');
              console.log(ele, 888);
              var opt = {
                margin: 7,
                filename: this.form.name,
                // image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2 },
                jsPDF: this.pdfConfig
              };
              const html2pdf = this.$html2pdf;
              setTimeout(() => {
                html2pdf().set(opt).from(ele).save();
                this.$message.success('导出成功！');
                this.visible = false;
                this.$emit('close', 'current');
                this.form.type = 'current';
              });
            });
          })
          .catch((e) => {
            this.$message.error('系统错误,请联系管理员!');
          });

        // this.handleSum();
      } catch (e) {
        Message({
          message: '请联系管理员',
          type: 'error'
        });
        console.log(e);
      }
    },
    handleClose() {
      this.form.type = 'current';
      this.visible = false;
      this.$emit('close', 'current');
    },
    // dicInit(type) {
    //   if (type === 'cascader') {
    //     this.handleLoadCascaderDic();
    //   } else {
    //     this.handleLoadDic();
    //   }
    // },
    getColumnOption() {
      let column = this._cloneDeep(this.option).column || [];
      let prop = [];
      const findProp = (list = []) => {
        list.forEach((ele, index) => {
          let children = ele.children;
          if (children && !Array.isArray(children)) delete ele.children;
          else if (ele.showColumn === false) list.splice(index, 1);
          else {
            prop.push(ele.prop);
            if (ele.children) findProp(children);
          }
        });
      };
      findProp(column);
      this.columnOption = column;
      this.newOption.column = column;
      this.$set(this.form, 'prop', prop);
    },
    // 获取导出的列
    getColumn() {
      let columns = this._cloneDeep(this.columnOption);
      let props = this.$refs.form.getPropRef('prop').$refs.temp.getHalfList();
      if (!this.form.params) return [];
      if (this.form.params.includes('headers')) {
        const findProp = (list = []) => {
          list.forEach((ele, index) => {
            if (!props.includes(ele.prop)) {
              list.splice(index, 1);
            } else if (ele.children) {
              findProp(ele.children);
            }
          });
        };
        findProp(columns);
        return columns;
      } else {
        let result = [];
        const findProp = (list = []) => {
          list.forEach((ele, index) => {
            if (ele.children) {
              findProp(ele.children);
            } else if (props.includes(ele.prop) || ele.level) {
              result.push(ele);
            }
          });
        };
        findProp(columns);
        return result.filter((item) => !item.hide || item.level);
      }
    },
    getPdfConfig(format_as_string, unit) {
      var pageFormats = {
        a0: [2383.94, 3370.39],
        a1: [1683.78, 2383.94],
        a2: [1190.55, 1683.78],
        a3: [841.89, 1190.55],
        a4: [595.28, 841.89],
        a5: [419.53, 595.28],
        a6: [297.64, 419.53],
        a7: [209.76, 297.64],
        a8: [147.4, 209.76],
        a9: [104.88, 147.4],
        a10: [73.7, 104.88],
        b0: [2834.65, 4008.19],
        b1: [2004.09, 2834.65],
        b2: [1417.32, 2004.09],
        b3: [1000.63, 1417.32],
        b4: [708.66, 1000.63],
        b5: [498.9, 708.66],
        b6: [354.33, 498.9],
        b7: [249.45, 354.33],
        b8: [175.75, 249.45],
        b9: [124.72, 175.75],
        b10: [87.87, 124.72],
        c0: [2599.37, 3676.54],
        c1: [1836.85, 2599.37],
        c2: [1298.27, 1836.85],
        c3: [918.43, 1298.27],
        c4: [649.13, 918.43],
        c5: [459.21, 649.13],
        c6: [323.15, 459.21],
        c7: [229.61, 323.15],
        c8: [161.57, 229.61],
        c9: [113.39, 161.57],
        c10: [79.37, 113.39],
        dl: [311.81, 623.62],
        letter: [612, 792],
        'government-letter': [576, 756],
        legal: [612, 1008],
        'junior-legal': [576, 360],
        ledger: [1224, 792],
        tabloid: [792, 1224],
        'credit-card': [153, 243]
      };
      switch (unit) {
        case 'pt':
          var k = 1;
          break;
        case 'mm':
          var k = 72 / 25.4;
          break;
        case 'cm':
          var k = 72 / 2.54;
          break;
        case 'in':
          var k = 72;
          break;
        case 'px':
          var k = 72 / 96;
          break;
        case 'pc':
          var k = 12;
          break;
        case 'em':
          var k = 12;
          break;
        case 'ex':
          var k = 6;
          break;
        default:
          throw 'Invalid unit: ' + unit;
      }
      return {
        format: pageFormats[format_as_string],
        k
      };
    },
    // //计算统计
    // handleSum() {
    //   const option = this.option;
    //   const columnOption = this.propOption;
    //   let list = this.data;
    //   let data = [];
    //   if (this.form.params.includes('data')) {
    //     list.forEach((ele) => {
    //       let obj = this.deepClone(ele);
    //       columnOption.forEach((column) => {
    //         let DIC = column.parentProp ? (this.cascaderDIC[row.$index] || {})[column.prop] : this.DIC[column.prop];
    //         obj[column.prop] = detail(obj, column, option, DIC);
    //         if (column['dicUrl'] || column['dicData']) {
    //           if (!column.formatter || !typeof column.formatter === 'function') {
    //             obj[column.prop] = obj[`$${column.prop}`];
    //           }
    //         }
    //       });
    //       data.push(obj);
    //     });
    //   }
    //   // 统计合计
    //   // if (this.form.params.includes('sum') && option.showSummary) {
    //   //   data.push(this.crud.sumsList);
    //   // }
    //   return data;
    // },
    //获取表格最新页面
    handleTableChange(values) {
      this.newOption.column = this.option.column.filter((item) => {
        return values.includes(item.prop);
      });
    }
    // //获取导出的数据
    // getData() {},
    // //选择开始的页码
    // handleSelectStartPage() {},
    // //选择结束的页码
    // handleSelectEndPage() {},
    // //本地字典
    // handleLocalDic() {
    //   loadLocalDic(this.resultOption, this);
    // },
    // handleChange(val) {
    //   this.$emit('selectData', val);
    // },
    // // 网络字典加载
    // handleLoadDic() {
    //   loadDic(this.resultOption, this);
    // },
    // //级联字典加载
    // handleLoadCascaderDic() {
    //   loadCascaderDic(this.propOption, this);
    // }
  }
};
</script>
<style lang="scss">
.custom-radio {
  width: 100%;
  height: 40px;
  line-height: 30px;
}
.pages-select {
  display: inline-block;
  .number-input {
    width: 100px;
  }
}

.pdf-warpper {
  margin: 10000px;
  opacity: 0;
}

.pdf-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
